import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from '@vant/auto-import-resolver';
import AutoImport from "unplugin-auto-import/vite"
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import viteCompression from 'vite-plugin-compression'
import path from 'path'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    Components({
      deep: true, // 搜索子目录
      dirs: ['src/components'], // 按需加载的文件夹
      dts: false,
      resolvers: [VantResolver()],
    }),
    AutoImport({
      // 自动导入配置开启eslintrc，避免变量未定义报错
      eslintrc: {
        enabled: true,
      },
      imports: ["vue", "vue-router", "pinia"],//自动引入vue的ref、toRefs、onmounted等，无需在页面中再次引入
      dts: false,
      resolvers: [VantResolver()],
    }),
    // 精灵图
    createSvgIconsPlugin({
      // 指定图标文件夹，绝对路径（NODE代码）
      iconDirs: [path.resolve(process.cwd(), 'src/icons')],
      // symbolId: 'icon-[name]',
    }),
    // gzip压缩
    viteCompression()
  ],
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler', // or 'modern'
        // scss全局变量
        additionalData: `
          @use "@/styles/mixin.scss";
          @use "@/styles/index.scss";
          `
      },
    },
  },
  // 路径别名
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    // 允许局域网访问vite服务
    host: '0.0.0.0',
    // 启动自动打开浏览器
    open: true,
    proxy: {
      '/api': {
        target: "http://localhost:8080",
        // 允许跨域
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
  // 打包配置
  build: {
    outDir: 'dist',
    // 静态资源
    assetsDir: 'assets',
    // 压缩
    minify: true,
    // 打包后删除console
    terserOptions: {
      compress: {
        drop_console: true,
      },
    },
  }
})
